package com.lanou.musicproject.utils;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.widget.SeekBar;
import android.os.Handler;
import android.util.Log;

import com.lanou.musicproject.bean.MySong;

import java.io.IOException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by ztq on 15/10/21.
 */
public class MusicPlayer extends MediaPlayer implements
        MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {

    public MediaPlayer mediaPlayer;
    private SeekBar seekBar;
    private Timer timer = new Timer();
    private List<MySong> song_data;
    public static int id = -1;
    public Context context;


    //seekbar没有实例化

    public MusicPlayer() {

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnPreparedListener(this);

        timer.schedule(timerTask, 0, 1000);
    }


    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            if (mediaPlayer == null)
                return;
            if (mediaPlayer.isPlaying())
                handler.sendEmptyMessage(0);
        }
    };


    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            int position = mediaPlayer.getCurrentPosition();
            int duration = mediaPlayer.getDuration();
            if (duration > 0) {
//                // 计算进度（获取进度条最大刻度*当前音乐播放位置 / 当前音乐时长）
//                long pos = seekBar.getMax() * position / duration;
//                seekBar.setProgress((int) pos);
            }
        }

        ;
    };


    public void play() {

            mediaPlayer.start();

    }

    public void playUrl(String url) {
        if (mediaPlayer != null) {
            try {
                Log.i("--------musicplayer", "playurl+++++++++++++++++");
                mediaPlayer.reset();
                mediaPlayer.setDataSource(url); // 设置数据源
                mediaPlayer.prepare(); // prepare自动播放
                mediaPlayer.start();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    // 暂停
    public void pause() {
        mediaPlayer.pause();
    }

    // 停止
    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }


    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }


    @Override
    public void onCompletion(MediaPlayer mp) {

    }


}
